package com.example.system.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.core.constants.HttpConstants;
import com.example.core.domain.LoginUser;
import com.example.core.domain.R;
import com.example.core.domain.VO.LoginUserVO;
import com.example.core.enums.ResultCode;
import com.example.core.enums.UserIdentity;
import com.example.core.utils.JwtUtils;
import com.example.scurity.exception.ServiceException;
import com.example.scurity.service.TokenService;
import com.example.scurity.utils.SecurityUtils;
import com.example.system.domain.sysUser.dto.SysUserDTO;
import com.example.system.domain.sysUser.po.SysUser;
import com.example.system.domain.sysUser.dto.SysUserSaveDto;
import com.example.system.mapper.SysUserMapper;
import com.example.system.service.ISysUserService;
import com.example.system.utils.BCryptUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RefreshScope
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {


    @Autowired
    private TokenService tokenService;

    @Resource
    private SysUserMapper sysUserMapper;
    @Value("${jwt.secret}")
    private String secret;

    //    @Override
//    public R<String> login(String userAccount, String password) {
//        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        SysUser sysUser = sysUserMapper.selectOne(lambdaQueryWrapper
//                .select(SysUser::getUserId, SysUser::getPassword,SysUser::getNickName)
//                .eq(SysUser::getUserAccount, userAccount)
//        );
//        if (sysUser == null) {
//            return R.fail(ResultCode.FAILED_PARAMS_VALIDATE);
//        }
//        if (BCryptUtils.matchesPassword(password, sysUser.getPassword())) {
//            String token = JwtUtils.createToken()
//            return R.ok(token);
//        }
//        return R.fail(ResultCode.FAILED_LOGIN);
//    }
    @Override
    public String login(SysUserDTO loginDTO) {
        SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserAccount, loginDTO.getUserAccount()));
        if (sysUser == null) {
            throw new ServiceException("当前登录用户不存在");
        }
//        if (!Md5Utils.verifyOriginalAndCiphertext(loginDTO.getPassword(), sysUser.getSalt(), sysUser.getPassword())) {
//            throw new ServiceException("账号或密码错误");
//        }
        if (!SecurityUtils.matchesPassword(loginDTO.getPassword(), sysUser.getPassword())) {
            throw new ServiceException("账号或密码错误");
        }
        //通过账号查找用户
        return assembleLoginUser(sysUser).getToken();
    }

    @Override
    public int add(SysUserSaveDto sysUserSaveDto) {

        List<SysUser> sysUserList = sysUserMapper.selectList(new
                LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserAccount, sysUserSaveDto.getUserAccount()));
        if (CollectionUtil.isNotEmpty(sysUserList)) {
            throw new ServiceException(ResultCode.AILED_USER_EXISTS);
        }

        SysUser sysUser = new SysUser();
        sysUser.setUserAccount(sysUserSaveDto.getUserAccount());
        sysUser.setPassword(BCryptUtils.encryptPassword(sysUserSaveDto.getPassword()));

        sysUser.setCreateBy(100L);
        sysUser.setCreateTime(LocalDateTime.now());
        return sysUserMapper.insert(sysUser);
    }

    @Override
    public R<LoginUserVO> info(String token) {
        if (StrUtil.isNotEmpty(token) &&
                token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        LoginUser loginUser = tokenService.getLoginUser(token);
        if (loginUser == null) {
            return R.fail();
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setNickName(loginUser.getNickName());
        return R.ok(loginUserVO);
    }



    private LoginUser assembleLoginUser(SysUser sysUser) {
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(sysUser, loginUser);
        loginUser.setIdentity(UserIdentity.ADMIN.getValue());
        return loginUser;
    }
}
